package com.dingding.transfer.stamper.handler;

import com.dingding.transfer.stamper.constant.StamperEnum;
import com.dingding.transfer.stamper.service.CmdStrategy;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/4/2 10:15
 **/
@Slf4j
public class CmdStrategyFactory {
    private static final String STRATEGY_PATH = "com.dingding.transfer.stamper.service.impl.";

    private static final String STRATEGY_SUFFIX = "Strategy";

    private static final Map<String,CmdStrategy> cacheStrategy = new ConcurrentHashMap<>();

    /**
     * 根据协议号 找到对应的处理策略。 这里设计规范要求 具体策略命名方式为 对应DTO名称 + Strategy
     * 例如： 同步申请单 ExistApplicationRes + Strategy,策略名称为ExistApplicationResStrategy
     * 这个类需要定义在包 Strategy_PATH下面,
     * @param code 协议号
     * @return
     */
    public static CmdStrategy getCmdStrategy(int code){
        String className = StamperEnum.getType(code).getSimpleName() + STRATEGY_SUFFIX;
        String completeName = STRATEGY_PATH + className;
        synchronized (CmdStrategyFactory.class){
            if(cacheStrategy.containsKey(className)){
                return cacheStrategy.get(className);
            }else{
                try {
                    CmdStrategy cmdStrategy = (CmdStrategy) Class.forName(completeName).newInstance();
                    cacheStrategy.put(className,cmdStrategy);
                    return cmdStrategy;
                } catch (Exception e) {
                    log.error("获取协议号{}对应策略失败,原因为{}",code,e.getMessage());
                }
            }
        }
        return null;
    }
}
